package com.markyao.service.impl;

import com.alibaba.fastjson.JSON;
import com.markyao.dao.pojo.SysUser;
import com.markyao.service.LoginService;
import com.markyao.service.SysUserService;
import com.markyao.utils.JWTUtils;
import com.markyao.utils.UserThreadLocal;
import com.markyao.vo.ErrorCode;
import com.markyao.vo.Result;
import com.markyao.vo.parmas.LoginParmas;
import com.markyao.vo.parmas.RegisterParmas;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.concurrent.TimeUnit;
@Service
@Transactional  //事务管理
public class LoginServiceImpl implements LoginService {
    @Autowired
    SysUserService sysUserService;
    @Autowired
    RedisTemplate<String,String>redisTemplate;
    private static final String md5mm = "123456Mky!@#$$";
    @Override
    public Result login(LoginParmas loginParmas) {
        /*
        1.检查参数是否合法
        2.根据用户名和密码查找数据库是否存在
        3.如果不存在登陆失败
        4.如果存在使用jwt 生成token返回前端
        5.token放入redis token:user信息 设置过期时间，登录认证的时候先认证token字符串是否合法，去redis认证是否存在。
         */
        String account = loginParmas.getAccount();
        String password = loginParmas.getPassword();
        if(StringUtils.isBlank(account)||StringUtils.isBlank(password)){
            return Result.failed(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }
        password= DigestUtils.md5Hex(password+md5mm);
        SysUser sysUser=sysUserService.findUser(account,password);
        if(sysUser==null){
            return Result.failed(ErrorCode.ACCOUNT_PWD_NOT_EXIST.getCode(), ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg());
        }
//        UserThreadLocal.put(sysUser);//将用户对象放入线程池
        String token = JWTUtils.createToken(sysUser.getId());
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        operations.set("TOKEN_"+token, JSON.toJSONString(sysUser),1, TimeUnit.DAYS);

        return Result.success(token);
    }

    @Override
    public SysUser checkT(String token) {
        if(StringUtils.isBlank(token)){
            return null;
        }
        Map<String, Object> map = JWTUtils.checkToken(token);
        if(map==null){
            return null;
        }
        String userJson = redisTemplate.opsForValue().get("TOKEN_" + token);
        if(StringUtils.isBlank(userJson)){
            return null;
        }
        SysUser sysUser = JSON.parseObject(userJson, SysUser.class);
        return sysUser;
    }

    @Override
    public Result logout(String token) {
        redisTemplate.delete("TOKEN_"+token);
        return Result.success(null);
    }

    @Override
    public Result register(RegisterParmas registerParmas) {
        /*
        注册用户
        1.检查参数是否有误
        2.查找用户是否已存在
        3.插入数据库
        4.生成token并写进redis，返回token
        5.事务管理，若是某个步骤有误回滚
         */
        String account = registerParmas.getAccount();
        String password = registerParmas.getPassword();
        String nickname = registerParmas.getNickname();
        //1
        if(StringUtils.isBlank(account)||StringUtils.isBlank(password)||StringUtils.isBlank(nickname)){
            return Result.failed(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }
        //2
        SysUser user=sysUserService.findUserByAccount(account);

        if(user!=null){
            return Result.failed(ErrorCode.ACCOUNT_EXIST_ERROR.getCode(), ErrorCode.ACCOUNT_EXIST_ERROR.getMsg());
        }
        SysUser sysUser=new SysUser();
        //3
        sysUser.setAccount(account);
        sysUser.setPassword(DigestUtils.md5Hex(password+md5mm));//md5加密
        sysUser.setNickname(nickname);
        sysUser.setCreateDate(System.currentTimeMillis());
        sysUser.setLastLogin(System.currentTimeMillis());
        sysUser.setAvatar("/static/img/logo.b3a48c0.png");
        sysUser.setAdmin(1); //1 为true
        sysUser.setDeleted(0); // 0 为false
        sysUser.setSalt("");
        sysUser.setStatus("");
        sysUser.setEmail("");
        sysUserService.insertOne(sysUser);

        //4
        String token = JWTUtils.createToken(sysUser.getId());
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        operations.set("TOKEN_"+token, JSON.toJSONString(sysUser),1, TimeUnit.DAYS);
        return Result.success(token);
    }
}
